// 引入公共头
$(function () {
    $('.header-common').load('../pages/header.html')
})
// 引入公共脚
$(function () {
    $('.footer-common').load('../pages/footer.html')
})
$()
// 去首页
function toIndex() {
    location.href = './index.html'
}
/**
 * 初始化swiper插件代码，必须放到模板数据加载完成html节点显示完成之后
 * @param {*}  
 */
function SwiperShow() {
    let mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal', // 垂直切换选项
        loop: true, // 循环模式选项
        autoplay: true,

        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },

        // 如果需要前进后退按钮
        // navigation: {
        //     nextEl: '.swiper-button-next',
        //     prevEl: '.swiper-button-prev',
        // }


    })
    //鼠标覆盖停止自动切换
    mySwiper.el.onmouseover = function () {
        mySwiper.autoplay.stop();
    }

    //鼠标离开开始自动切换
    mySwiper.el.onmouseout = function () {
        mySwiper.autoplay.start();
    }
}

/**
 * 获取商品信息
 */
function goodList() {
    let product = JSON.parse(localStorage.getItem('product')).data
    detailsShow(product)
    SwiperShow()
    addCart(product)
}
goodList()
/**
 * 商品描述 商家店铺详情显示
 */
function detailsShow(product) {
    // banner显示
    let bannerImgs = product.detail.photo
    let str = ''
    bannerImgs.forEach(item => {
        str += `
            <div class="swiper-slide">
                <img src="${item.url}" alt="商品图">
            </div>
        `
    });
    $('.swiper-wrapper').html(str)

    // 过期时间 product.detail.coupon.expireDate
    // 券 product.detail.couponValue
    // 原价product.detail.originPrice
    // 现价product.detail.price
    // 多少人已买 product.detail.saleNum
    // console.log(goodDesc)
    // 标题

    // 商品详细信息
    $('.goods_title').html(product.detail.title)

    // 价格 
    let price = `
        <span class="before_pri">原价￥：${product.detail.originPrice}</span>
        <div class="price_buy">
            <span class="price">券后价：￥<span class="point"><span
            class="int">${parseInt(product.detail.price)}</span>.${cutStr(product.detail.price.toString())}</span><span class="details_ticket">${product.detail.couponValue}</span></span>
            <span class="buy">${product.detail.saleNum}人已买</span>
        </div>
    `
    $('.goods_price').html(price)

    let time = `
        优惠有效期：${product.detail.coupon.expireDate}
    `
    $('.goods_time').html(time)

    $('.shopLogo').attr('src', product.shop.coverUrl)
    $('.shop_name').html(product.shop.nickname)
    $('.shop_desc>li>span').eq(0).html(product.shop.itemScore)
    $('.shop_desc>li>span').eq(1).html(product.shop.serviceScore)
    $('.shop_desc>li>span').eq(2).html(product.shop.deliveryScore)

    // 商品图片
    let imglistsStr = ''
    let pro_lists = product.detail.descContentList
    pro_lists.forEach(item => {
        imglistsStr += `
            <img src="${item.image.url}" alt="">
    `
    })

    $('.pro_products').html(imglistsStr)

}

/**
 * 放大镜
 */
function BigGrass() {
    // 显示与隐藏
    $('.bigGra').on('mouseover', function () {
        $('.grass').css('display', 'block')
        $('.bigGrass').css('display', 'block')
    })
    $('.bigGra').on('mouseout', function () {
        $('.grass').css('display', 'none')
        $('.bigGrass').css('display', 'none')
    })
    $('.swiper-pagination').on('mouseover', function () {
        event.stopPropagation();
        $('.grass').css('display', 'none')
        $('.bigGrass').css('display', 'none')
    })

    // 跟随鼠标 放大镜
    $('.bigGra').on('mousemove', function (e) {
        e = e || window.event
        let mouseX = e.offsetX
        let mouseY = e.offsetY

        let x = mouseX - parseInt($('.grass').css('width')) / 2
        let y = mouseY - parseInt($('.grass').css('height')) / 2

        // 边界判断
        if (x < 0) x = 0
        if (y < 0) y = 0

        if (x > parseInt($('.bigGra').css('width')) - (parseInt($('.grass').css('width'))))
            x = parseInt($('.bigGra').css('width')) - parseInt($('.grass').css('width'))
        if (y > parseInt($('.bigGra').css('height')) - (parseInt($('.grass').css('height'))))
            y = parseInt($('.bigGra').css('height')) - parseInt($('.grass').css('height'))



        $('.grass').css('left', `${x}px`)
        $('.grass').css('top', `${y}px`)

        // 大图
        let sideStr = $('.swiper-pagination-bullet-active').attr('aria-label')
        let index = cutPage(sideStr)
        let bigIng_src = $('.swiper-slide').children().eq(index).attr('src')
        $('.bigIng_src').attr('src', bigIng_src)

        // 大图大小
        let ImgWidth = parseInt($('.bigGra').css('width')) * parseInt($('.bigGrass').css('width')) / parseInt($('.grass').css('width'))
        $('.bigGrass').children().css('width', ImgWidth + 'px')

        // 大图移动
        let bigImgMoveX = x * parseInt($('.bigIng_src').css('width')) / parseInt($('.bigGra').css('width'))
        let bigImgMoveY = y * parseInt($('.bigIng_src').css('height')) / parseInt($('.bigGra').css('height'))
        $('.bigIng_src').css('left', -bigImgMoveX + 'px')
        $('.bigIng_src').css('top', -bigImgMoveY + 'px')

    })



}
BigGrass()

function cutPage(sideStr) {
    let newArr = sideStr.split(' ')
    return newArr[3]
}
/**
 * 加入购物车
 */
function addCart(goodsInfo) {
    goodsId = goodsInfo.detail.id
    console.log(goodsId)
    $('.tocart').click(function () {
        // 获取他的id 调用接口获得信息存locaStorage
        let products = JSON.parse(localStorage.getItem('products')) || []
        if (products.length == 0) {
            goodsInfo = {
                ...goodsInfo,
                cartNum: 1,
                singlePrice: 0,
                state: false,
            }
            products.push(goodsInfo)
        } else {
            let isGoods = []
            isGoods = products.find(item => goodsId == item.detail.id)
            console.log('isGoods', isGoods)
            if (isGoods) {
                isGoods.cartNum++
            } else {
                goodsInfo = {
                    ...goodsInfo,
                    cartNum: 1,
                    singlePrice: goodsInfo.detail.price,
                    state: false,
                }
                products.push(goodsInfo)
            }
        }
        console.log('goodsInfo.cartNum', goodsInfo.cartNum)

        localStorage.setItem('products', JSON.stringify(products))
        alert('加入购物车成功！')
    })
}

/**
 * 跳转购物车
 */
function toCart() {
    $('.cart_icon').click(function () {
        location.href = './cart.html'
    })
}
toCart()

/**
 * 取价格的小数部分
 * @param {} str 
 * @returns 
 */
function cutStr(str) {
    let newArr = str.split('.')
    return newArr[1]
}

/**
 * 返回顶部
 */
 window.onscroll = function () {
    toTop()
}
function toTop() {
    if (document.body.scrollTop >= 600 || document.documentElement.scrollTop >= 600) {
        $('.toTop').css('display', 'block')
    } else if (document.body.scrollTop < 600 || document.documentElement.scrollTop < 600) {
        $('.toTop').css('display', 'none')
    }

    $('.toTop').click(function () {
        document.body.scrollTop = 0
        document.documentElement.scrollTop = 0
    })
}
